import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:wms/utils/utils.dart';
import '/models/LoadTaskData.dart';
import '../../services/api_service.dart';
import '../../services/auth_service.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';

class LoadTaskScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;

  const LoadTaskScreen({super.key, required this.jsonData});

  @override
  _LoadTaskScreenState createState() => _LoadTaskScreenState();
}

class _LoadTaskScreenState extends State<LoadTaskScreen> with WidgetsBindingObserver {
  
  LoadTaskData? taskData;
  LoadLine? selectedLpn;
  final TextEditingController itemNumberController = TextEditingController();
  final TextEditingController quantityController = TextEditingController();
  final FocusNode _itemNumberFocusNode = FocusNode();
  final FocusNode _scanFocusNode = FocusNode();

  // Quantity 专属控制
  final FocusNode _quantityFocusNode = FocusNode();
  bool _quantityKeyboardVisible = false;
  double _keyboardHeight = 0;

  String? itemNumber;
  String? lpnNumber;
  String? orderNumber;
  String? packKey;
  String? internalItemNumber;
  String? loadNumber;
  int? loadId;
  String _scanBuffer = '';
  DateTime? _lastKeyTime;
  int? warehouseId;
  List<LoadLine> availableLpns = [];
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;
  int maxAllowedValue = 0;
  bool _isLoading = false;

  static const double _bottomButtonAreaHeight = 120;
  static const double _appBarHeight = 56;

  // 统一样式
  TextStyle get _detailLabelStyle => TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 12 * _fontScale,
      );

  TextStyle get _detailValueStyle => TextStyle(
        fontSize: 12 * _fontScale,
      );

  TextStyle get _listTitleStyle => TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: baseFontSize * _fontScale,
      );

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 解析初始化数据
    loadNumber = widget.jsonData['loadNumber'];
    loadId = widget.jsonData['loadId'];
    _initData();
    
    // Quantity 焦点监听
    _quantityFocusNode.addListener(_handleQuantityFocusChange);
    
    // 扫描焦点设置
    _scanFocusNode.canRequestFocus = true;
    _scanFocusNode.addListener(() {
      if (mounted && _scanFocusNode.hasFocus) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            FocusScope.of(context).requestFocus(_itemNumberFocusNode);
          }
        });
      }
    });
    
    // Item Number 焦点监听
    _itemNumberFocusNode.addListener(() {
      if (mounted && _itemNumberFocusNode.hasFocus && itemNumberController.text.isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            itemNumberController.selection = TextSelection(
              baseOffset: 0,
              extentOffset: itemNumberController.text.length,
            );
          }
        });
      }
    });
  }

  // 带重试的焦点请求
  void _requestItemFocusWithRetry([int retryCount = 0]) {
    if (retryCount >= 5) {
      print('聚焦重试5次失败，检查输入框是否渲染');
      return;
    }

    Future.delayed(Duration(milliseconds: 300 * retryCount), () {
      if (!mounted) return;

      final inputRenderObject = _itemNumberFocusNode.context?.findRenderObject();
      if (inputRenderObject == null || !inputRenderObject.attached) {
        print('第${retryCount+1}次聚焦失败：输入框未渲染，将重试');
        _requestItemFocusWithRetry(retryCount + 1);
        return;
      }

      // 取消其他焦点，确保Item输入框聚焦
      _quantityFocusNode.unfocus();
      FocusScope.of(context).unfocus();
      FocusScope.of(context).requestFocus(_itemNumberFocusNode);

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          if (_itemNumberFocusNode.hasFocus) {
            print('第${retryCount+1}次聚焦成功：Item Number输入框已聚焦');
            // 聚焦后滚动到顶部
            final scrollController = PrimaryScrollController.of(context);
            if (scrollController != null) {
              scrollController.animateTo(
                0,
                duration: const Duration(milliseconds: 200),
                curve: Curves.easeInOut
              );
            }
            // 激活扫描焦点
            FocusScope.of(context).requestFocus(_scanFocusNode);
          } else {
            print('第${retryCount+1}次聚焦失败，将重试');
            _requestItemFocusWithRetry(retryCount + 1);
          }
        }
      });
    });
  }

  Future<void> _initData() async {
    if (loadNumber == null) return;

    try {
      final authService = Provider.of<AuthService>(context, listen: false);
      final user = authService.currentUser;
      warehouseId = user?.warehouse;

      final jsonData = await getLoadLine(loadNumber!);
      if (mounted) {
        setState(() {
          taskData = LoadTaskData.fromJson(jsonData);
          availableLpns = taskData?.loadLines ?? [];
        });

        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _requestItemFocusWithRetry();
          }
        });
      }
    } catch (e) {
      if (mounted) {
        MessageBox.showMessageBox(context, '初始化失败: $e', isError: true);
        setState(() => taskData = null);
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _requestItemFocusWithRetry();
          }
        });
      }
    }
  }

  // 监听键盘显示/隐藏事件
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        final newKeyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        if (newKeyboardHeight != _keyboardHeight) {
          setState(() {
            _keyboardHeight = newKeyboardHeight;
            if (newKeyboardHeight == 0 && _quantityKeyboardVisible) {
              _quantityKeyboardVisible = false;
              _quantityFocusNode.unfocus();
            }
          });
        }
      }
    });
  }

  // 后台返回时处理
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
      FocusScope.of(context).requestFocus(_itemNumberFocusNode);
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          final scrollController = PrimaryScrollController.of(context);
          if (scrollController != null) {
            scrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeInOut);
          }
          FocusScope.of(context).requestFocus(_scanFocusNode);
        }
      });
    }
  }

  // Quantity 焦点变化处理
  void _handleQuantityFocusChange() {
    if (mounted) {
      setState(() {
        _quantityKeyboardVisible = _quantityFocusNode.hasFocus;
      });

      if (_quantityFocusNode.hasFocus) {
        _showKeyboard();
        _scanFocusNode.unfocus();
        
        Future.delayed(const Duration(milliseconds: 250), () {
          if (mounted && _quantityFocusNode.context != null) {
            Scrollable.ensureVisible(
              _quantityFocusNode.context!,
              duration: const Duration(milliseconds: 200),
              curve: Curves.easeInOut,
              alignment: 0.1,
            );
          }
        });
      } else {
        _hideKeyboard();
        if (_itemNumberFocusNode.hasFocus) {
          FocusScope.of(context).requestFocus(_scanFocusNode);
        }
      }
    }
  }

  // 显示系统键盘
  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示Quantity键盘失败: $e');
    }
  }

  // 隐藏系统键盘
  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏Quantity键盘失败: $e');
    }
  }

  // 切换Quantity键盘
  void _toggleQuantityKeyboard() {
    if (!mounted) return;

    setState(() {
      _quantityKeyboardVisible = !_quantityKeyboardVisible;
    });

    if (_quantityKeyboardVisible) {
      _itemNumberFocusNode.unfocus();
      _quantityFocusNode.requestFocus();
      Future.delayed(const Duration(milliseconds: 150), () => _showKeyboard());
    } else {
      _quantityFocusNode.unfocus();
      Future.delayed(const Duration(milliseconds: 150), () {
        if (mounted) {
          _hideKeyboard();
          FocusScope.of(context).requestFocus(_itemNumberFocusNode);
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              FocusScope.of(context).requestFocus(_scanFocusNode);
            }
          });
        }
      });
    }
  }

  // 重置所有键盘状态
  void _resetAllKeyboards() {
    if (mounted) {
      setState(() {
        _quantityKeyboardVisible = false;
      });
      _quantityFocusNode.unfocus();
      _hideKeyboard();
      if (_itemNumberFocusNode.hasFocus) {
        FocusScope.of(context).requestFocus(_scanFocusNode);
      }
    }
  }

  // 获取Load数据
  Future<Map<dynamic, dynamic>> getLoadLine(String loadNumber) async {
    var apiUrl = ApiService.baseURL + ApiService.fetchLoad;

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }

    final responsedata = await http.get(
      Uri.parse(apiUrl + loadNumber),
      headers: {
        'Authorization': 'JWT $accessToken',
        'x-warehouse-id': '$warehouseId',
        'x-timezone': 'America/Los_Angeles',
        'Content-Type':'application/json',
        'X-Client-Type':'app'
      },
    );
    String responseBody = utf8.decode(responsedata.bodyBytes);
    Map<String, dynamic> jsonData = json.decode(responseBody);
    
    if(jsonData['code'] == 2000){
      return jsonData['data'];
    }
    else if(jsonData['code'] == 401){
      AuthService auth = AuthService();
      auth.logout(context);
      throw Exception('The session has expired, Please log in again.');
    }
    else {
      throw Exception('${jsonData['msg']}');
    }
  }

  // 订单详情
  Map<String, String> get orderDetails => {
        'Equipment': taskData?.equipment ?? 'N/A',
        'Load': taskData?.loadNumber ?? 'N/A',
      };

  // 获取shipment数据
  Future<Map<String, dynamic>> fetchshipmentLine() async {
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchshipmentLine}order_number=${orderNumber!.trim()}&pack_key=${packKey!.trim()}';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }
  
  // 选择LPN
  void _handleLpnSelection(LoadLine lpn) {
    _resetAllKeyboards();
    
    setState(() {
      if (selectedLpn == lpn) {
        selectedLpn = null;
        itemNumberController.clear();
        quantityController.clear();
        maxAllowedValue = 0;
      } else {
        selectedLpn = lpn;
        itemNumberController.text = lpn.itemNumber;
        quantityController.text = lpn.quantity.toString();
        maxAllowedValue = lpn.quantity;
        
        itemNumberController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: lpn.itemNumber.length,
        );
      }
    });
    
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        FocusScope.of(context).requestFocus(_itemNumberFocusNode);
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            FocusScope.of(context).requestFocus(_scanFocusNode);
          }
        });
      }
    });
  }

  // 继续按钮
  void _continue() async {
    _resetAllKeyboards();
    
    if (taskData == null) {
      MessageBox.showMessageBox(context, '数据未加载完成', isError: true);
      return;
    }

    try {
      Navigator.pushNamed(
        context,
        '/inbound/putaway-summary',
        arguments: {'loadNumber': loadNumber, 'loadId': loadId},
      );
    } catch (e) {
      MessageBox.showMessageBox(context, e, isError: true);
    }
  }

  // 移除LPN
  void _removeLpn() async {
    _resetAllKeyboards();
    
    if (selectedLpn == null) return;
    if (taskData == null) {
      MessageBox.showMessageBox(context, '数据未加载完成', isError: true);
      return;
    }
    
    try {
      Map<dynamic, dynamic> responeData = await _callRemoveApi(selectedLpn!.id);

      if (responeData['code'] == 2000 && mounted) {
        setState(() {
          taskData!.loadLines.remove(selectedLpn);
          selectedLpn = null;
          itemNumberController.clear();
          quantityController.clear();
        });
        MessageBox.showMessageBox(context, responeData['msg'], isError: false);
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted) {
            FocusScope.of(context).requestFocus(_itemNumberFocusNode);
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                FocusScope.of(context).requestFocus(_scanFocusNode);
              }
            });
          }
        });
      } else {
        MessageBox.showMessageBox(context, responeData['msg'], isError: true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e, isError: true);
    }
  }

  // 调用移除API
  Future<Map<dynamic, dynamic>> _callRemoveApi(int id) async {
    final apiUrl = ApiService.baseURL + ApiService.deleteLoadLine;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    try {
      var requestBody = {'load_line': id};
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 处理扫描输入（核心修复：确保文本更新）
  void _handleScanInput(String value) async {
    print('扫描原始内容: $value');
    try {
      itemNumber = Utils.parseQRCode(value, 'item number');
      lpnNumber = Utils.parseQRCode(value, 'lpn number');
      orderNumber = Utils.parseQRCode(value, 'order number');
      packKey = Utils.parseQRCode(value, 'pack key');
      internalItemNumber = Utils.parseQRCode(value, 'product code');
      
      print('解析结果 - itemNumber: $itemNumber');
      
      final displayValue = itemNumber ?? value;
      
      // 强制更新UI
      if (mounted) {
        setState(() {
          itemNumberController.text = displayValue;
          itemNumberController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: displayValue.length,
          );
        });
      }
      
      if (itemNumber != null) {
        Map<String, dynamic> shipmentLineData = await fetchshipmentLine();
        var quantity = shipmentLineData['data']['received_quantity'] ?? '0';
        if (mounted) {
          setState(() {
            quantityController.text = quantity.toString();
            maxAllowedValue = int.parse(quantity.toString());
          });
        }
      }
    } catch (e) {
      print('扫描处理失败: $e');
      if (mounted) {
        setState(() {
          itemNumberController.text = value;
          itemNumberController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: value.length,
          );
        });
      }
      MessageBox.showMessageBox(context, e, isError: true);
    } finally {
      // 确保焦点状态正确
      if (mounted) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            if (!_itemNumberFocusNode.hasFocus) {
              FocusScope.of(context).requestFocus(_itemNumberFocusNode);
            }
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                FocusScope.of(context).requestFocus(_scanFocusNode);
              }
            });
          }
        });
      }
    }
  }

  // 处理扫描枪键盘事件（核心修复：确保事件捕获）
  void _handleKeyEvent(KeyEvent event) {
    if (event is KeyDownEvent) {
      final now = DateTime.now();
      // 调整扫描判断阈值为300ms，提高兼容性
      if (_lastKeyTime != null && now.difference(_lastKeyTime!) > const Duration(milliseconds: 300)) {
        print('检测到手动输入，清空扫描缓冲区');
        _scanBuffer = '';
        return;
      }
      _lastKeyTime = now;

      final key = event.logicalKey;
      print('扫描按键事件: ${key.keyLabel} (${key.debugName})');

      // 处理所有可能的回车事件（包括数字键盘回车）
      if (key == LogicalKeyboardKey.enter || 
          key == LogicalKeyboardKey.numpadEnter) {
        print('检测到Enter键，扫描结束，缓冲区内容: $_scanBuffer');
        if (_scanBuffer.isNotEmpty) {
          _handleScanInput(_scanBuffer);
          _scanBuffer = '';
        }
      } else {
        final character = event.character;
        if (character != null && character.isNotEmpty) {
          _scanBuffer += character;
          print('缓冲区更新: $_scanBuffer');
        }
      }
    }
  }

  // 添加LPN
  Future<void> _addLpn() async {
    _resetAllKeyboards();
    
    if (taskData == null) {
      MessageBox.showMessageBox(context, '数据未加载完成', isError: true);
      return;
    }

    try {
      final itemNumber = itemNumberController.text.trim();
      final quantity = quantityController.text.trim();

      if (itemNumber.isEmpty || quantity.isEmpty) {
        throw Exception('Item number or quantity can`t be null.');
      }
      if (internalItemNumber == null) {
        throw Exception('Please scan barcode.');
      }

      Map<dynamic, dynamic> response = await _callAddApi(
        itemNumber: itemNumber,
        quantity: int.parse(quantity),
      );

      if (response['code'] == 2000 && mounted) {
        final newLpnData = response['data'] as Map<String, dynamic>;
        
        setState(() {
          itemNumberController.clear();
          quantityController.clear();
          internalItemNumber = null;

          taskData!.loadLines.add(LoadLine(
            id: newLpnData['id'],
            lpnNumber: newLpnData['lpn_number'] ?? 'N/A',
            itemNumber: newLpnData['item_number'] ?? 'N/A',
            quantity: newLpnData['quantity'] ?? 0,
            itemName: newLpnData['item_name'] ?? 'N/A',
            itemDesc: newLpnData['item_desc'] ?? 'N/A',
            packKey: newLpnData['pack_key'] ?? 'N/A',
            status: newLpnData['status'] ?? 'N/A',
          ));
        });
        
        MessageBox.showMessageBox(context, response['msg'], isError: false);
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            FocusScope.of(context).requestFocus(_itemNumberFocusNode);
            FocusScope.of(context).requestFocus(_scanFocusNode);
          }
        });
      } else if (response['code'] != 2000 && mounted) {
        MessageBox.showMessageBox(context, response['msg'], isError: false);
      }
    } catch (e) {
      if (!mounted) return;
      MessageBox.showMessageBox(context, e, isError: true);
    }
  }

  // 调用添加API
  Future<Map<dynamic, dynamic>> _callAddApi({
    required String itemNumber,
    required int quantity,
  }) async {
    if (taskData == null) {
      throw Exception('数据未加载完成');
    }

    final apiUrl = ApiService.baseURL + ApiService.createLoadLine;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    final requestBody = {
      'id': null,
      'load': taskData!.id,
      'warehouse': warehouseId,
      'order_number': orderNumber,
      'lpn_number': lpnNumber ?? taskData!.lpnNumber,
      'item_number': itemNumber,
      'quantity': quantity,
      'pack_key': packKey ?? taskData!.packKey,
      'internal_item_number': internalItemNumber
    };

    try {
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final screenHeight = mediaQuery.size.height;
    final contentMaxHeight = screenHeight - _appBarHeight - _bottomButtonAreaHeight;
    
    return MediaQuery(
      data: mediaQuery.copyWith(
        textScaler: TextScaler.linear(isSmallScreen ? 0.85 : 1.0),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Load Task', style: TextStyle(fontSize: 18 * _fontScale)),
          automaticallyImplyLeading: false,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/inbound/putaway');
            },
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.home, color: Colors.white),
              onPressed: () {
                _resetAllKeyboards();
                Navigator.pushNamed(context, '/home');
              },
            ),
          ],
          backgroundColor: const Color(0xFF008363),
        ),
        resizeToAvoidBottomInset: false,
        body: Stack(
          children: [
            // 主内容区域
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              bottom: _bottomButtonAreaHeight,
              child: GestureDetector(
                onTap: () {
                  _resetAllKeyboards();
                  FocusScope.of(context).unfocus();
                },
                behavior: HitTestBehavior.opaque,
                child: _isLoading
                    ? const Center(child: CircularProgressIndicator())
                    : Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: isSmallScreen ? 12 : 32,
                          vertical: 12,
                        ),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(maxHeight: contentMaxHeight),
                          child: SingleChildScrollView(
                            controller: PrimaryScrollController.of(context) ?? ScrollController(),
                            physics: const ClampingScrollPhysics(),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                if (taskData != null)
                                  ..._buildOrderDetails(isSmallScreen)
                                else
                                  const Padding(
                                    padding: EdgeInsets.symmetric(vertical: 15),
                                    child: Center(child: Text('Loading...')),
                                  ),
                                const SizedBox(height: 8),
                                
                                if (taskData != null)
                                  Text('Items:', style: _listTitleStyle)
                                else
                                  const SizedBox.shrink(),
                                const SizedBox(height: 6),
                                
                                if (taskData != null)
                                  Container(
                                    height: 160,
                                    decoration: BoxDecoration(
                                      border: Border.all(color: Colors.grey, width: 1.0),
                                      borderRadius: BorderRadius.circular(4.0),
                                    ),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(4.0),
                                      child: ClipRect(
                                        child: availableLpns.isEmpty
                                            ? const Center(child: Text('No Items available'))
                                            : ListView.builder(
                                                physics: const ClampingScrollPhysics(),
                                                shrinkWrap: true,
                                                itemCount: availableLpns.length,
                                                itemBuilder: (context, index) {
                                                  final lpn = availableLpns[index];
                                                  final isSelected = selectedLpn == lpn;

                                                  final nameLabelStyle = TextStyle(
                                                    fontSize: listFontSize * _fontScale,
                                                    color: isSelected ? Colors.green : Colors.black87,
                                                  );
                                                  final nameValueStyle = TextStyle(
                                                    fontSize: listFontSize * _fontScale,
                                                    fontWeight: FontWeight.bold,
                                                    color: isSelected ? Colors.green : Colors.black87,
                                                  );

                                                  return InkWell(
                                                    onTap: () => _handleLpnSelection(lpn),
                                                    child: Container(
                                                      margin: const EdgeInsets.symmetric(vertical: 1),
                                                      decoration: BoxDecoration(
                                                        border: Border.all(
                                                          color: const Color.fromARGB(255, 169, 168, 168), 
                                                          width: 0.5
                                                        ),
                                                        borderRadius: BorderRadius.circular(4.0),
                                                        color: isSelected ? Colors.green[50] : null,
                                                      ),
                                                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                                      child: Column(
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          Row(
                                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                            children: [
                                                              Text(
                                                                lpn.itemNumber,
                                                                style: TextStyle(
                                                                  fontSize: listFontSize * _fontScale,
                                                                  fontWeight: FontWeight.bold,
                                                                  color: isSelected ? Colors.green : Colors.black,
                                                                ),
                                                              ),
                                                              Expanded(
                                                                child: Padding(
                                                                  padding: const EdgeInsets.only(left: 8),
                                                                  child: Row(
                                                                    mainAxisAlignment: MainAxisAlignment.end,
                                                                    children: [
                                                                      Text('Name: ', style: nameLabelStyle),
                                                                      Text(
                                                                        lpn.itemName,
                                                                        style: nameValueStyle,
                                                                        overflow: TextOverflow.ellipsis,
                                                                        maxLines: 1,
                                                                      ),
                                                                    ],
                                                                  ),
                                                                ),
                                                              ),
                                                            ],
                                                          ),
                                                          const SizedBox(height: 3),
                                                          
                                                          Row(
                                                            children: [
                                                              Expanded(
                                                                flex: 1,
                                                                child: Row(
                                                                  mainAxisSize: MainAxisSize.min,
                                                                  children: [
                                                                    Text(
                                                                      'LPN: ',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                      ),
                                                                    ),
                                                                    Text(
                                                                      lpn.lpnNumber ?? 'N/A',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                        fontWeight: FontWeight.bold,
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              ),
                                                              
                                                              Expanded(
                                                                flex: 1,
                                                                child: Row(
                                                                  mainAxisSize: MainAxisSize.min,
                                                                  children: [
                                                                    Text(
                                                                      'Qty: ',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                      ),
                                                                    ),
                                                                    Text(
                                                                      '${lpn.quantity ?? 0}',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                        fontWeight: FontWeight.bold,
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              ),
                                                              
                                                              Expanded(
                                                                flex: 1,
                                                                child: Row(
                                                                  mainAxisSize: MainAxisSize.min,
                                                                  children: [
                                                                    Text(
                                                                      'Status: ',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                      ),
                                                                    ),
                                                                    Text(
                                                                      lpn.status ?? 'N/A',
                                                                      style: TextStyle(
                                                                        fontSize: listFontSize * _fontScale,
                                                                        color: isSelected ? Colors.green : Colors.black87,
                                                                        fontWeight: FontWeight.bold,
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              ),
                                                            ],
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  );
                                                },
                                              ),
                                      ),
                                    )
                                  )
                                else
                                  const Center(child: CircularProgressIndicator()),
                                const SizedBox(height: 8),
                                
                                // 输入框区域
                                AnimatedPadding(
                                  padding: EdgeInsets.only(
                                    bottom: _quantityKeyboardVisible ? _keyboardHeight : 0,
                                  ),
                                  duration: const Duration(milliseconds: 200),
                                  curve: Curves.easeInOut,
                                  child: _buildLpnInputSection(isSmallScreen),
                                ),
                                
                                const SizedBox(height: 10),
                              ],
                            ),
                          ),
                        ),
                      ),
              ),
            ),
            
            // 底部按钮区域
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              height: _bottomButtonAreaHeight,
              child: Container(
                color: Theme.of(context).scaffoldBackgroundColor,
                padding: EdgeInsets.symmetric(
                  horizontal: isSmallScreen ? 12 : 20,
                  vertical: 10,
                ),
                child: Column(
                  children: [
                    _buildButton('Add', taskData != null ? _addLpn : null),
                    const SizedBox(height: 6),
                    _buildButton('Remove', (taskData != null && selectedLpn != null) ? _removeLpn : null),
                    const SizedBox(height: 6),
                    _buildButton('Continue', taskData != null ? _continue : null),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建订单详情
  List<Widget> _buildOrderDetails(bool isSmallScreen) {
    if (taskData == null) return [];
    
    return orderDetails.entries.map((entry) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 2),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: isSmallScreen ? 100 : 120,
              child: Text('${entry.key}:', style: _detailLabelStyle),
            ),
            const SizedBox(width: 6),
            Expanded(child: Text(entry.value, style: _detailValueStyle)),
          ],
        ),
      );
    }).toList();
  }

  // 构建输入框区域
  Widget _buildLpnInputSection(bool isSmallScreen) {
    final InputDecoration inputDecoration = InputDecoration(
      border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
      contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
      isDense: true,
    );

    final double inputHeight = 28;
    return Column(
      children: [
        // Item Number 输入框
        Padding(
          padding: const EdgeInsets.only(bottom: 6),
          child: Row(
            children: [
              _buildInputLabel('Item Number:'),
              const SizedBox(width: 32),
              Expanded(
                child: KeyboardListener(
                  focusNode: _scanFocusNode,
                  onKeyEvent: _handleKeyEvent,
                  child: SizedBox(
                    height: inputHeight,
                    child: TextField(
                      controller: itemNumberController,
                      keyboardType: TextInputType.none,
                      focusNode: _itemNumberFocusNode,
                      decoration: inputDecoration,
                      style: TextStyle(fontSize: baseFontSize * _fontScale),
                      enabled: true,
                      onChanged: (value) {
                        if (mounted && _itemNumberFocusNode.hasFocus) {
                          itemNumberController.selection = TextSelection(
                            baseOffset: 0,
                            extentOffset: value.length,
                          );
                        }
                      },
                      
                      onTap: () {
                        if (mounted) {
                          _quantityFocusNode.unfocus();
                          FocusScope.of(context).requestFocus(_itemNumberFocusNode);
                          WidgetsBinding.instance.addPostFrameCallback((_) {
                            if (mounted) {
                              FocusScope.of(context).requestFocus(_scanFocusNode);
                            }
                          });
                        }
                      },
                      onSubmitted: _handleScanInput,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        
        // Quantity 输入框
        Padding(
          padding: const EdgeInsets.only(top: 6),
          child: Row(
            children: [
              _buildInputLabel('Quantity:'),
              const SizedBox(width: 32),
              Expanded(
                child: SizedBox(
                  height: inputHeight,
                  child: TextField(
                    controller: quantityController,
                    focusNode: _quantityFocusNode,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      RangeInputFormatter(maxAllowedValue)
                    ],
                    decoration: inputDecoration.copyWith(
                      suffixIcon: IconButton(
                        icon: Icon(
                          _quantityKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                          color: const Color(0xFF008363),
                          size: isSmallScreen ? 16 : 18,
                        ),
                        onPressed: _toggleQuantityKeyboard,
                        splashRadius: 16,
                        padding: const EdgeInsets.all(0),
                        constraints: const BoxConstraints.tightFor(width: 28, height: 28),
                      ),
                    ),
                    keyboardType: TextInputType.number,
                    style: TextStyle(fontSize: baseFontSize * _fontScale),
                    enabled: taskData != null,
                    onTap: () {
                      if (mounted && quantityController.text.isNotEmpty) {
                        quantityController.selection = TextSelection(
                          baseOffset: 0,
                          extentOffset: quantityController.text.length,
                        );
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 构建输入框标签
  Widget _buildInputLabel(String text) {
    return SizedBox(
      width: 90,
      height: 28,
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          text,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: baseFontSize * _fontScale
          ),
        ),
      ),
    );
  }

  // 构建按钮
  Widget _buildButton(String text, VoidCallback? onPressed) {
    return SizedBox(
      width: double.infinity,
      height: 28,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: onPressed != null ? const Color(0xFF008363) : Colors.grey,
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.0)),
        ),
        child: Text(
          text,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: baseFontSize * _fontScale,
            color: Colors.white
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _quantityFocusNode.removeListener(_handleQuantityFocusChange);
    
    _itemNumberFocusNode.dispose();
    _scanFocusNode.dispose();
    _quantityFocusNode.dispose();
    itemNumberController.dispose();
    quantityController.dispose();
    
    super.dispose();
  }
}
